package marchenko.springdao.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import marchenko.springdao.domain.Genre;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class GenreRepositoryImpl implements GenreRepository {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	public Genre find(Integer id) throws DataAccessException {
		return jdbcTemplate.queryForObject("select * from genres where id = ?",
				new GenreMapper(), id);
	}

	public Genre findByName(String name) throws DataAccessException {
		return jdbcTemplate.queryForObject(
				"select * from genres where name = ?", new GenreMapper(), name);
	}

	public List<Genre> findAll() throws DataAccessException {
		return jdbcTemplate.query("select * from genres", new GenreMapper());
	}

	public boolean create(Genre newinstance) throws DataAccessException {
		return jdbcTemplate.update("insert into genres values (?,?)",
				newinstance.getGenreId(),
				newinstance.getGenreName()) > 0;
	}

	public boolean deleteById(Integer id) throws DataAccessException {
		return jdbcTemplate.update("delete from genres where id = ?", id) > 0;
	}

	private static final class GenreMapper implements RowMapper<Genre> {

		public Genre mapRow(ResultSet resultSet, int i) throws SQLException {
			Genre genre = new Genre();
			genre.setGenreId(resultSet.getInt("id"));
			genre.setGenreName(resultSet.getString("name"));
			return genre;
		}
	}

}
